﻿// Copyright 2009 Mike Geise
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Falcon.Core.SqlServer.Repositories.Parameters
{
	using System;
	using System.Data;
	using System.Data.SqlClient;
	using Falcon.Core.Domain;
	using Falcon.Core.Extensions;

	public class UserSearchParameter : IParameter<UserSearch>
	{
		/// <summary>
		/// Populates the specified parameters.
		/// </summary>
		/// <param name="parameters">The parameters.</param>
		/// <param name="entity">The entity.</param>
		public void Populate(SqlParameterCollection parameters, UserSearch entity)
		{
			if (entity.UserId > 0)
			{
				parameters.Add("@UserID", SqlDbType.Int).Value = entity.UserId;
				parameters.Add("@Title", SqlDbType.NVarChar).Value = entity.Title;
			}

			parameters.Add("@Name", SqlDbType.NVarChar).Value = entity.Name.GetValueOrNull();
			parameters.Add("@EmailAddress", SqlDbType.NVarChar).Value = entity.EmailAddress.GetValueOrNull();
			parameters.Add("@HostAddress", SqlDbType.NVarChar).Value = entity.HostAddress.GetValueOrNull();

			if (entity.CreatedAfter.HasValue())
			{
				parameters.Add("@JoinedAfter", SqlDbType.DateTime).Value = DateTime.Parse(entity.CreatedAfter);
			}

			if (entity.CreatedBefore.HasValue())
			{
				parameters.Add("@JoinedBefore", SqlDbType.DateTime).Value = DateTime.Parse(entity.CreatedBefore);
			}

			if (entity.LastVisitAfter.HasValue())
			{
				parameters.Add("@ActivityAfter", SqlDbType.DateTime).Value = DateTime.Parse(entity.LastVisitAfter);
			}

			if (entity.LastVisitBefore.HasValue())
			{
				parameters.Add("@ActivityBefore", SqlDbType.DateTime).Value = DateTime.Parse(entity.LastVisitBefore);
			}

			parameters.Add("@PostsGreaterThanOrEqual", SqlDbType.Int).Value = entity.PostsGreaterThanOrEqual;

			if (entity.PostsLessThanOrEqual > 0)
			{
				parameters.Add("@PostsLessThanOrEqual", SqlDbType.Int).Value = entity.PostsLessThanOrEqual;
			}

			parameters.Add("@ReputationGreaterThanOrEqual", SqlDbType.Int).Value = entity.ReputationGreaterThanOrEqual;

			if (entity.ReputationLessThanOrEqual > 0)
			{
				parameters.Add("@ReputationLessThanOrEqual", SqlDbType.Int).Value = entity.ReputationLessThanOrEqual;
			}

			parameters.Add("@Created", SqlDbType.DateTime).Value = entity.Created;
			parameters.Add("@Updated", SqlDbType.DateTime).Value = entity.Updated;
		}
	}
}